// pages/main_shell.dart
import 'package:flutter/material.dart';
import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:go_router/go_router.dart';

import 'ai_chat/ai_chat_page.dart';

class MainShell extends StatefulWidget {
  final Widget child;
  const MainShell({super.key, required this.child});

  @override
  State<MainShell> createState() => _MainShellState();
}

class _MainShellState extends State<MainShell> {

  // 添加变量保存上次选中的索引
  int _lastSelectedIndex = 0;
  int _calculateSelectedIndex(BuildContext context) {
    // 返回保存的索引而非根据路由计算
    return _lastSelectedIndex;
  }
  // int _calculateSelectedIndex(BuildContext context) {
  //   final String location = GoRouterState.of(context).matchedLocation;
  //   if (location.startsWith('/home')) {
  //     return 0;
  //   }
  //   if (location.startsWith('/report')) {
  //     return 1;
  //   }
  //   if (location.startsWith('/ai')) {
  //     return 2;
  //   }
  //   if (location.startsWith('/services')) {
  //     return 3;
  //   }
  //   if (location.startsWith('/profile')) {
  //     return 4;
  //   }
  //   return 0;
  // }

  void _onItemTapped(int index, BuildContext context) {
    if (index != 2) {
    setState(() {
      // _lastSelectedIndex = index;
    });
    }

    switch (index) {
      case 0:
        GoRouter.of(context).go('/home');
        break;
      case 1:
        GoRouter.of(context).go('/report');
        break;
      case 2:
        GoRouter.of(context).push('/ai');
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(builder: (context) => const AiChatPage()),
        // );

        break;
      case 3:
        GoRouter.of(context).go('/services');
        break;
      case 4:
        GoRouter.of(context).go('/profile');
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: widget.child,
      bottomNavigationBar: ConvexAppBar(
        style: TabStyle.fixedCircle,
          top: -10, // 控制凸起的垂直位置
          // cornerRadius: 67,
          curveSize: 50,
          height: 50, // 添加这一行来控制整体高度
        backgroundColor: Colors.white,
        activeColor: const Color(0xFF4DD0E1),
        color: Colors.grey,
        items: const [
          TabItem(icon: Icons.home, title: '首页'),
          TabItem(icon: Icons.bar_chart, title: '报表'),
          TabItem(icon: Icons.bubble_chart, title: 'AI'),
          TabItem(icon: Icons.favorite_border, title: '服务'),
          TabItem(icon: Icons.person, title: '我的'),
        ],
        initialActiveIndex: _lastSelectedIndex,
        // initialActiveIndex: _calculateSelectedIndex(context),
        onTap: ( index) {
          if (index == 2) {
            // 第三个选项卡：仅跳转不更新状态
            GoRouter.of(context).push('/ai');
          } else {
            _onItemTapped(index, context);
          }
        }
      ),
    );
  }
}